const db = require("../config/db");

exports.getAll = async () => {
  const [rows] = await db.query("SELECT * FROM customers");
  return rows;
};

exports.add = async (customer) => {
  const {
    wechatId,
    name,
    phone,
    address,
    balance = 0,
    points = 0,
    registerDate,
    source,
  } = customer;
  const [result] = await db.query(
    "INSERT INTO customers (wechatId,name,phone,address,balance,points,registerDate,source) VALUES (?,?,?,?,?,?,?,?)",
    [wechatId, name, phone, address, balance, points, registerDate, source]
  );
  return { id: result.insertId, ...customer };
};

exports.update = async (id, customer) => {
  const {
    wechatId,
    name,
    phone,
    address,
    balance,
    points,
    registerDate,
    source,
  } = customer;
  await db.query(
    "UPDATE customers SET wechatId=?,name=?,phone=?,address=?,balance=?,points=?,registerDate=?,source=? WHERE id=?",
    [wechatId, name, phone, address, balance, points, registerDate, source, id]
  );
  return { id, ...customer };
};

exports.remove = async (id) => {
  await db.query("DELETE FROM customers WHERE id=?", [id]);
};

exports.getBalanceDetails = async (id) => {
  const [rows] = await db.query(
    "SELECT * FROM balance_details WHERE customerId=?",
    [id]
  );
  return rows;
};
